package algorithm;

public class IsHappy {
    public static int compute(int n) {
        //计算快乐数的函数
        int sum = 0;

        while(n > 0) {
            int tmp = n%10;
            sum += tmp*tmp;
            n /= 10;
        }

        return sum;
    }
    public static boolean isHappy(int n) {
        //利用寻找链表中环的算法思想
        int left = n,right = compute(n);

        while(left != right) {
            //left走一步
            //right走两步
            left = compute(left);
            right = compute(compute(right));
        }

        //代码走到这里说明left和right相遇了，此时判断left和right是否等于1即可
        // 如果是，则说明是快乐数，如果不是，说明不是快乐数
        if(left == 1) {
            return true;
        } else {
            return false;
        }
    }
    public static void main(String[] args) {
        int n = 19;
        System.out.println(isHappy(2));
    }
}
